package com.fhx.core.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;

import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class ApplicationUtil {
    //获取当前进程名
    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> lists = mActivityManager.getRunningAppProcesses();
        if (lists != null) {
            for (RunningAppProcessInfo appProcess : lists) {
                if (appProcess.pid == pid) {
                    return appProcess.processName;
                }
            }
        } else {
            //有时候没获取到就认为是当前包名
            return context.getPackageName();
        }
        return null;
    }

    //获取meta值
    public static String getMetaDataValue(Context context, String key) {
        try {
            ApplicationInfo ai = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            return ai.metaData.getString(key);
        } catch (Exception e) {
            //
        }
        return null;
    }
    public static String getMetaDataKey(Context context, String value){
        try {
            ApplicationInfo ai = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            Bundle metaBundle = ai.metaData;
            Set<String> keySet = metaBundle.keySet();  //获取所有的Key
            if(keySet != null && keySet.size()>0){
                for(String str:keySet){
                    if(value.equals(metaBundle.getString(str))){
                        return str;
                    }
                }
            }
        } catch (Exception e) {
            //
        }
        return null;
    }
    /**
     * 获取应用程序名称
     *
     * @return String
     */
    public static String getAppName(Context context) {
        return getAppName(context, null);
    }

    /**
     * 获取应用程序名称
     *
     * @param packageName
     * @return String
     */
    public static String getAppName(Context context, String packageName) {
        String applicationName;

        if (TextUtils.isEmpty(packageName)) {
            packageName = context.getPackageName();
        }

        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    packageName, 0);
            applicationName = context
                    .getString(packageInfo.applicationInfo.labelRes);
        } catch (Exception e) {
            applicationName = "";
        }

        return applicationName;
    }

    /**
     * 获取版本名称
     *
     * @return String
     */
    public static String getAppVersionName(Context context) {
        return getAppVersionName(context, null);
    }

    /**
     * 获取版本名称
     *
     * @param packageName
     * @return String
     */
    public static String getAppVersionName(Context context, String packageName) {
        String versionName;

        if (packageName == null) {
            packageName = context.getPackageName();
        }

        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    packageName, 0);
            versionName = packageInfo.versionName;
        } catch (Exception e) {
            versionName = "";
        }

        return versionName;
    }

    /**
     * 获取应用程序的版本号
     *
     * @return int
     */
    public static int getAppVersionCode(Context context) {
        return getAppVersionCode(context, null);
    }

    /**
     * 获取指定应用程序的版本号
     *
     * @param packageName
     * @return int
     */
    public static int getAppVersionCode(Context context, String packageName) {
        int versionCode = 0;

        if (packageName == null) {
            packageName = context.getPackageName();
        }

        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    packageName, 0);
            versionCode = packageInfo.versionCode;
        } catch (Exception e) {
            versionCode = 0;
        }

        return versionCode;
    }

    /***
     * 获取top的Activity的ComponentName
     *
     * @param paramContext
     * @return
     */
    public static ComponentName getTopActivityCompomentName(Context paramContext) {
        List<RunningTaskInfo> localList = null;
        if (paramContext != null) {
            ActivityManager localActivityManager = (ActivityManager) paramContext
                    .getSystemService(Context.ACTIVITY_SERVICE);
            if (localActivityManager != null) {
                localList = localActivityManager.getRunningTasks(1);

                if ((localList == null) || (localList.size() <= 0)) {
                    return null;
                }
            }
        }
        ComponentName localComponentName = localList.get(0).topActivity;
        return localComponentName;
    }

    // 是否是最顶层是应用，即当前用户正在操作的应用
    public static boolean isTopApplication(Context context) {
        String packageName = context.getPackageName();
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
        if (tasksInfo.size() > 0) {
            if (packageName.equals(tasksInfo.get(0).topActivity
                    .getPackageName()))
                return true;
        }
        return false;
    }

    /***
     * 是否后台
     *
     * @param paramContext
     * @return
     */
    public static boolean isAppRunningBackground(Context paramContext) {
        String pkgName = null;
        List<RunningAppProcessInfo> localList = null;
        if (paramContext != null) {
            pkgName = paramContext.getPackageName();
            ActivityManager localActivityManager = (ActivityManager) paramContext
                    .getSystemService(Context.ACTIVITY_SERVICE);
            if (localActivityManager != null) {
                localList = localActivityManager.getRunningAppProcesses();
                if ((localList == null) || (localList.size() <= 0)) {
                    return false;
                }
            }
        }

        for (Iterator<RunningAppProcessInfo> localIterator = localList
                .iterator(); localIterator.hasNext(); ) {
            RunningAppProcessInfo info = localIterator.next();
            if (info.processName.equals(pkgName)
                    && info.importance != RunningAppProcessInfo.IMPORTANCE_VISIBLE
                    && info.importance != RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }

    public static void hideApp(Activity activity, boolean nonRoot) {
        if (activity != null)
            activity.moveTaskToBack(nonRoot);
    }

    public static void showDesk(Context context) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        context.startActivity(intent);
    }

    // 打开应用市场，可以进行评价
    public static void gotoMarket(Activity activity) {
        Uri localUri = Uri.parse("market://details?id="
                + activity.getPackageName());
        Intent localIntent = new Intent("android.intent.action.VIEW", localUri);
        // localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//加上这个之后会另起一个栈，返回的时候可能不会返回到当前应用了
        activity.startActivity(localIntent);
    }

    // 打开应用市场，可以进行评价
    public static boolean gotoMarket(Activity activity, String pkgName) {
        try {
            Uri localUri = Uri.parse("market://details?id="
                    + pkgName);
            Intent localIntent = new Intent("android.intent.action.VIEW", localUri);
            // localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//加上这个之后会另起一个栈，返回的时候可能不会返回到当前应用了
            activity.startActivity(localIntent);
            return true;
        } catch (Exception e) {

        }
        return false;
    }

    /**
     * 查询隐式意图默认Activitiy
     *
     * @param context
     * @param intent
     * @return
     */
    public ResolveInfo queryDefaultActivity(Context context, Intent intent) {
        PackageManager pm = context.getPackageManager();
        //Intent intent = new Intent(Intent.ACTION_VIEW);
        //intent.setData(Uri.parse("http://www.baidu.com"));
        ResolveInfo info = pm.resolveActivity(intent,
                PackageManager.MATCH_DEFAULT_ONLY);
        return info;
    }

    /**
     * 判断某个程序是否安装在手机中
     *
     * @param context     上下文
     * @param packageName 需要验证的包名
     * @return 是否安装
     */
    public static boolean isPackageExist(Context context, String packageName) {
        if (packageName == null)
            return false;
        boolean packageExist = false;
        PackageManager packageManager = context.getPackageManager();
        try {
            packageManager.getPackageInfo(packageName, 0);
            packageExist = true;
        } catch (PackageManager.NameNotFoundException ignored) {
        }
        return packageExist;
    }

}